#include<stdio.h>
#include "../include/vfs.h"
#include<stdlib.h>
#include<string.h>
#include "../include/over_write.h"


int movefile( char source[], char destin[])
{

	FD *dest,*src,*src_exist,*dest_exist,*src_exist1=NULL,*dest_par=NULL,*dest_exist1=NULL;
	source_exist=0;
	movefile_err=0;
	int i=0;
	char *new_path,f[2]="/",parent_dest[80],final[50],fname[50];

	for(i=0;i<80;i++)
	{
		parent_dest[i]='\0';
	}

	for(i=0;i<50;i++)
	{
		final[i]='\0';
	}

	for(i=0;i<50;i++)
	{
		fname[i]='\0';
	}

	if(strcmp(source,"")==0)
			return 3;

	if(strcmp(destin,"")==0)
			return 4;

	if(destin[strlen(destin)-1]=='/' && strlen(destin)>2)
	{
		destin[strlen(destin)-1]='\0';
	}
	
	

	new_path = strtok(destin,"/");

	if(new_path==NULL)
	{
		//parent_dest = malloc(sizeof(char)*100);
		strcpy(parent_dest,"/");
	}

	else
	{	//parent_dest = malloc(sizeof(char)*100);

	while(new_path!=NULL)
	{
		
		strcat(parent_dest,"/");
		strcpy(final,parent_dest);
		strcpy(fname,new_path);
		strcat(parent_dest,new_path);

		new_path = strtok(NULL,"/");
	}

	}

	if(strlen(final)>2)
		final[strlen(final)-1]='\0';
	else
	{
		for(i=0;i<50;i++)
		{
		final[i]='\0';
		}
		strcpy(final,"/");
	}	
	
	fname[strlen(fname)]='\0';

	dest = malloc(sizeof(FD));
	src = malloc(sizeof(FD));

	dest_exist = malloc(sizeof(FD));
	dest_par = malloc(sizeof(FD));
	src_exist = malloc(sizeof(FD));

	strcpy(dest->path,parent_dest);
	strcpy(src->path,source);
	strcpy(dest_par->path,final);

	//printf("\n PAR: %s\nfinal:%s\n fname:%s\n",parent_dest,final,fname);

		src_exist1 = search(roots.naryroot,src);

		if(src_exist1==NULL)
			return 1;

		if(src_exist1->file_type==0)
			return 2;

		dest_exist1 = search(roots.naryroot,dest);
		
		if(dest_exist1==NULL)
		{
			dest_exist1 = search(roots.naryroot,dest_par);
			
			if(dest_exist1==NULL)
				return 2;
		
			else
			{
				hash_deletion(src);
				roots.naryroot = move_file(roots.naryroot,dest_par,src,1,fname);
				delete_bst(src->path,roots.bstRoot);
			}
		}
	
		else
		{
			if(dest_exist1->file_type>0)
			{
				
				overwrite(dest,src);
				hash_deletion(src);
				roots.naryroot = delete_root(roots.naryroot,src);
				delete_bst(src->path,roots.bstRoot);
			}
								
			else
			{
				hash_deletion(src);
				roots.naryroot = move_file(roots.naryroot,dest_par,src,1,fname);
				delete_bst(src->path,roots.bstRoot);
				
			}

		}

	return 0;
}

